import { defineStore } from 'pinia'
import { getSpeciesRelationTask } from '~/api/searchApi'

interface Option {
    value: string
    label: string
}

interface SpeciesState {
    genusOptions: Option[]
    speciesData: Record<string, string[]>
    loading: boolean
    error: string | null
}

export const useSpeciesStore = defineStore('species', {
    state: (): SpeciesState => ({
        genusOptions: [],
        speciesData: {},
        loading: false,
        error: null
    }),
    actions: {
        async fetchSpeciesRelation(strainType: 'Medicinal' | 'Bacterial' = 'Medicinal') {
            this.loading = true
            this.error = null
            try {
                const response = await getSpeciesRelationTask({ strainType })

                if (response.success && response.data) {
                    // 转换API返回的数据格式
                    this.genusOptions = response.data.genus.map(genus => ({
                        value: genus,
                        label: genus
                    }))

                    // 转换species数据格式
                    this.speciesData = response.data.species
                } else {
                    throw new Error(response.error || 'Failed to fetch species data')
                }
            } catch (error: any) {
                this.error = error.message
                console.error('Error fetching species relation:', error)
            } finally {
                this.loading = false
            }
        },

        // 获取所有种名选项（去重）
        getAllSpeciesOptions(): Option[] {
            const allSpecies = Object.values(this.speciesData).flat()
            const uniqueSpecies = [...new Set(allSpecies)]

            return uniqueSpecies.map(species => ({
                value: species,
                label: species
            }))
        },

        // 获取种名到属名的映射
        getSpeciesToGenusMap(): Record<string, string> {
            const map: Record<string, string> = {}
            Object.entries(this.speciesData).forEach(([genus, speciesList]) => {
                speciesList.forEach(species => {
                    map[species] = genus
                })
            })
            return map
        }
    }
})